package com.controller;

import com.biz.IUserInfoBiz;
import com.entity.Userinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserAction {

    @Autowired
    private IUserInfoBiz biz;

    public IUserInfoBiz getBiz() {
        return biz;
    }

    public void setBiz(IUserInfoBiz biz) {
        this.biz = biz;
    }


    //登录
    @RequestMapping("/log")
    @ResponseBody
    public void  log(HttpSession sess, String uname, String pwd, HttpServletResponse res) throws IOException {
        Userinfo user=biz.log(uname,pwd);
        if(user!=null)
        {
            sess.setAttribute("loger",user);
            if(user.getIsadmin()>0){
                res.getWriter().print("<script>location='../back/back-index.jsp';</script>");
            }
            else
            {
                res.getWriter().print("<script>location='../index.jsp';</script>");
            }

        }else
        {
            res.getWriter().print( "<script>alert('用户名或密码错误,请重新登录！');location=history.go(-1);</script>");
        }
    }


    //列表
    @RequestMapping("/list")
    @ResponseBody
    public List getAll()
    {
        List list= biz.getAll();
        return list;
    }

    //增加
    @RequestMapping("/add")
    public String addUser(Userinfo userinfo)
    {
        biz.addUser(userinfo);
        return "../back/userlist";
    }

    //修改前获取一个
    @RequestMapping("/selectById")
    public ModelAndView selectById(int id)
    {
        ModelAndView mv=new ModelAndView("back/user-mod");
        Userinfo userinfo=biz.selectById(id);
        mv.addObject("user",userinfo);
        return  mv;
    }

    //修改
    @RequestMapping("/mod")
    public String modUser(Userinfo userinfo)
    {
        biz.modUser(userinfo);
        return "/back/userlist";
    }

    //删除
    @RequestMapping("/del")
    public String delUser(int id)
    {
        System.out.println("进来了============id"+id);
        biz.delUser(id);
        return "/back/userlist";
    }

    //退出登录
    @RequestMapping("/doexit")
    public String doexit(HttpSession session){
        session.invalidate();//销毁跟用户关联session
        return "index";
    }

}
